// dh-reviews 云对象 - 评价管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getUserList } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-reviews] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 职称等级转换文本
 */
function getTitleText(titleLevel) {
	const titleMap = {
		0: '医士',
		1: '医师',
		2: '主治医师',
		3: '副主任医师',
		4: '主任医师'
	};
	return titleMap[titleLevel] || '未知';
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-reviews] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	async getReviewById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '评价ID不能为空');
			}

			const res = await db.collection('dh-reviews').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '评价不存在');
			}
			return formatResponse(200, res.data[0]);
		} catch (error) {
			return formatError(error, '获取评价失败');
		}
	},

	async listReviews(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			// 默认不显示已删除记录
			query.is_deleted = false;
			
			const res = await db.collection('dh-reviews')
				.where(query)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();
			
			// 获取所有唯一的评价人ID
			const reviewerIds = [...new Set(res.data.map(item => item.reviewer_id).filter(Boolean))];
			
			// 获取所有评价医生的target_id (review_type = 1)
			const doctorTargetIds = [...new Set(
				res.data
					.filter(item => item.review_type === 1)
					.map(item => item.target_id)
					.filter(Boolean)
			)];
			
			// 查询评价人信息（使用统一的用户查询工具）
			let reviewerMap = {};
			if (reviewerIds.length > 0) {
				// 使用 getUserList 批量查询用户信息（可能包含患者和医生）
				const allUsers = await getUserList({
					format: 'default',
					limit: 1000,
					decryptSensitiveInfo: true,
					allowPatients: true
				});
				
				// 构建用户ID到用户信息的映射
				allUsers.forEach(user => {
					if (reviewerIds.includes(user._id)) {
						reviewerMap[user._id] = {
							nickname: user.nickname || '',
							username: user.username || '',
							real_name: user.realName || ''
						};
					}
				});
			}
			
			// 查询医生信息
			let doctorMap = {};
			if (doctorTargetIds.length > 0) {
				// target_id 指向的是 dh-doctors._id，不是 user_id
				const doctorRes = await db.collection('dh-doctors')
					.where({
						_id: _.in(doctorTargetIds)
					})
					.field({
						_id: true,
						user_id: true,
						title_level: true
					})
					.get();
				
				// 收集医生的 user_id 用于查询用户表
				const doctorUserIds = doctorRes.data.map(d => d.user_id);
				
				// 使用统一的用户查询工具获取医生真实姓名
				let userNameMap = {};
				if (doctorUserIds.length > 0) {
					// 使用 getUserList 批量查询医生信息
					const allDoctors = await getUserList({
						includeRoles: ['doctor'],
						format: 'default',
						limit: 1000,
						decryptSensitiveInfo: true
					});
					
					// 构建用户ID到姓名的映射
					allDoctors.forEach(user => {
						if (doctorUserIds.includes(user._id)) {
							userNameMap[user._id] = user.realName || user.displayName || '未知';
						}
					});
				}
				
				// 组合医生信息，key 使用 doctor._id（即评价的 target_id）
				doctorRes.data.forEach(doctor => {
					const doctorName = userNameMap[doctor.user_id] || '未知';
					const title = getTitleText(doctor.title_level);
					
					doctorMap[doctor._id] = {
						doctor_id: doctor._id,
						doctor_name: doctorName,
						title: title
					};
				});
			}
			
			// 将用户信息和医生信息附加到评价数据
			const enrichedData = res.data.map(item => {
				const reviewerInfo = reviewerMap[item.reviewer_id] || {};
				const doctorInfo = item.review_type === 1 ? (doctorMap[item.target_id] || {}) : {};
				
				return {
					...item,
					reviewer_info: reviewerInfo,
					doctor_info: doctorInfo
				};
			});
			
			// 获取总数
			const countRes = await db.collection('dh-reviews')
				.where(query)
				.count();
			
			return formatResponse(200, enrichedData, 'success', { count: countRes.total });
		} catch (error) {
			return formatError(error, '获取评价列表失败');
		}
	},

	async createReview(data) {
		try {
			if (!data.patient_id || !data.doctor_id || !data.rating) {
				return formatResponse(400, null, '患者、医生和评分不能为空');
			}

			if (data.rating < 1 || data.rating > 5) {
				return formatResponse(400, null, '评分必须在1-5之间');
			}

		let reviewData = {
			patient_id: data.patient_id,
			patient_name: data.patient_name || '',
			doctor_id: data.doctor_id,
			doctor_name: data.doctor_name || '',
			appointment_id: data.appointment_id || '',
			rating: data.rating,
			comment: data.comment || '',
			tags: data.tags || [],
			is_anonymous: data.is_anonymous !== undefined ? data.is_anonymous : false,
			is_verified_purchase: data.is_verified_purchase !== undefined ? data.is_verified_purchase : true,
			helpful_count: 0,
			unhelpful_count: 0,
			is_deleted: false,  // 软删除字段，默认未删除
			create_time: Date.now(),
			update_time: Date.now()
		};

		// 🏥 自动挂载医院ID（单一医院系统特性）
		reviewData = await autoMountHospitalId(reviewData);

		const res = await db.collection('dh-reviews').add(reviewData);
			return formatResponse(201, { _id: res.id }, '评价创建成功');
		} catch (error) {
			return formatError(error, '创建评价失败');
		}
	},

	async updateReview(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '评价ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-reviews').doc(id).update(updateData);
			return formatResponse(200, null, '评价更新成功');
		} catch (error) {
			return formatError(error, '更新评价失败');
		}
	},

	async deleteReview(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '评价ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-reviews', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '评价已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除评价失败');
		}
	},

	async batchUpdateReviews(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-reviews').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	async batchDeleteReviews(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-reviews', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	async getDoctorReviews(doctorId, skip = 0, limit = 20) {
		try {
			if (!doctorId) {
				return formatResponse(400, null, '医生ID不能为空');
			}

			const res = await db.collection('dh-reviews')
				.where({ doctor_id: doctorId })
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();

			if (res.data.length === 0) {
				return formatResponse(200, [], 'success', { count: 0, average_rating: 0 });
			}

			const avgRating = res.data.reduce((sum, r) => sum + r.rating, 0) / res.data.length;

			return formatResponse(200, res.data, 'success', {
				count: res.data.length,
				average_rating: Math.round(avgRating * 10) / 10
			});
		} catch (error) {
			return formatError(error, '获取医生评价失败');
		}
	},

	async markHelpful(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '评价ID不能为空');
			}

			await db.collection('dh-reviews').doc(id).update({
				helpful_count: _.inc(1),
				update_time: Date.now()
			});

			return formatResponse(200, null, '感谢您的反馈');
		} catch (error) {
			return formatError(error, '标记评价失败');
		}
	}
};
